package com.example.administrator.express.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.administrator.express.R;
import com.example.administrator.express.http.HttpClient;
import com.example.administrator.express.http.HttpResponseHandler;
import com.example.administrator.express.model.ViewCount;
import com.example.administrator.express.model.delivery_view;
import com.example.administrator.express.model.sign_view;
import com.example.administrator.express.utils.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.ColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;
import okhttp3.FormBody;
import okhttp3.Request;

public class LineColumnDependencyActivity extends ActionBarActivity {
    public static String posttype;

    static double countformonth[] = new double[12];


static  Integer btnid;



    public void splita() {
        if (getIntent().getExtras().getInt("btnid") == 4) {
            btnid=4;
            countformonth = getIntent().getExtras().getDoubleArray("receive");
//            SharedPreferences sharedPreferences=SharedPreferences.getInstance();
//            String a =sharedPreferences.getString("receivecountformonth","");
//            String[] temp = a.split(" ");//以空格拆分字符串
//            for(
//                    int i = 0; i<temp.length;i++)
//            {
//                countformonth[i] = Double.parseDouble(temp[i]);//整数数组
//            }
        } else if (getIntent().getExtras().getInt("btnid") == 5) {
            btnid=5;
            countformonth = getIntent().getExtras().getDoubleArray("delivery");
//            SharedPreferences sharedPreferences=SharedPreferences.getInstance();
//            String a =sharedPreferences.getString("deliverycountformonth","");
//            String[] temp = a.split(" ");//以空格拆分字符串
//            for(
//                    int i = 0; i<temp.length;i++)
//            {
//                countformonth[i] = Double.parseDouble(temp[i]);//整数数组
//            }
        } else if (getIntent().getExtras().getInt("btnid") == 6) {
            btnid=6;
            countformonth = getIntent().getExtras().getDoubleArray("sign");
//            SharedPreferences sharedPreferences=SharedPreferences.getInstance();
//            String a =sharedPreferences.getString("signcountformonth","");
//            String[] temp = a.split(" ");//以空格拆分字符串
//            for(
//                    int i = 0; i<temp.length;i++)
//            {
//                countformonth[i] = Double.parseDouble(temp[i]);//整数数组
//            }
        } else {

        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line_column_dependency);
        splita();

        //    countformonth=getIntent().getExtras().getDoubleArray("countformonth");


        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }


    }


    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        List<ViewCount> list1 = new ArrayList<ViewCount>();
        List<delivery_view> list2 = new ArrayList<delivery_view>();
        List<sign_view> list3 = new ArrayList<sign_view>();
        Integer countformonthaaa[] = new Integer[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        public final static String[] months = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
                "Sep", "Oct", "Nov", "Dec",};

        public final static String[] days = new String[]{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
        public final static String[] date = new String[]{"2016-01", "2016-02", "2016-03", "2016-04", "2016-05", "2016-06", "2016-07", "2016-08", "2016-09", "2016-10", "2016-11", "2016-12"};



        private LineChartView chartTop;
        private ColumnChartView chartBottom;

        private LineChartData lineData;
        private ColumnChartData columnData;

        public PlaceholderFragment() {
        }


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_line_column_dependency, container, false);

            // *** TOP LINE CHART ***
            chartTop = (LineChartView) rootView.findViewById(R.id.chart_top);


            // Generate and set data for line chart
            generateInitialLineData();

            // *** BOTTOM COLUMN CHART ***

            chartBottom = (ColumnChartView) rootView.findViewById(R.id.chart_bottom);


            generateColumnData();

            return rootView;
        }


        private void generateColumnData() {

            int numSubcolumns = 1;
            int numColumns = months.length;

            List<AxisValue> axisValues = new ArrayList<AxisValue>();
            List<Column> columns = new ArrayList<Column>();
            List<SubcolumnValue> values;

            for (int i = 0; i < numColumns; ++i) {

                values = new ArrayList<SubcolumnValue>();
                for (int j = 0; j < numSubcolumns; ++j) {
                    values.add(new SubcolumnValue((float) countformonth[i], ChartUtils.pickColor()));
                }
//countformonth[i]*1.0f
                axisValues.add(new AxisValue(i).setLabel(months[i]));

                columns.add(new Column(values).setHasLabelsOnlyForSelected(true));
            }

            columnData = new ColumnChartData(columns);

            columnData.setAxisXBottom(new Axis(axisValues).setHasLines(true));
            columnData.setAxisYLeft(new Axis().setHasLines(true).setMaxLabelChars(2));

            chartBottom.setColumnChartData(columnData);

            // Set value touch listener that will trigger changes for chartTop.
            chartBottom.setOnValueTouchListener(new ValueTouchListener());

            // Set selection mode to keep selected month column highlighted.
            chartBottom.setValueSelectionEnabled(true);

            chartBottom.setZoomType(ZoomType.HORIZONTAL);

            // chartBottom.setOnClickListener(new View.OnClickListener() {
            //
            // @Override
            // public void onClick(View v) {
            // SelectedValue sv = chartBottom.getSelectedValue();
            // if (!sv.isSet()) {
            // generateInitialLineData();
            // }
            //
            // }
            // });

        }

        /**
         * Generates initial data for line chart. At the begining all Y values are equals 0. That will change when user
         * will select value on column chart.
         */
        private void generateInitialLineData() {
            int numValues = 31;

            List<AxisValue> axisValues = new ArrayList<AxisValue>();
            List<PointValue> values = new ArrayList<PointValue>();
            for (int i = 0; i < numValues; ++i) {
                values.add(new PointValue(i,countformonthaaa[i]));
                axisValues.add(new AxisValue(i).setLabel(days[i]));
            }

            Line line = new Line(values);
            line.setColor(ChartUtils.COLOR_GREEN).setCubic(true);

            List<Line> lines = new ArrayList<Line>();
            lines.add(line);

            lineData = new LineChartData(lines);
            lineData.setAxisXBottom(new Axis(axisValues).setHasLines(true));
            lineData.setAxisYLeft(new Axis().setHasLines(true).setMaxLabelChars(3));

            chartTop.setLineChartData(lineData);

            // For build-up animation you have to disable viewport recalculation.
            chartTop.setViewportCalculationEnabled(false);

            // And set initial max viewport and current viewport- remember to set viewports after data.
            Viewport v = new Viewport(0, 5, 31, 0);
            chartTop.setMaximumViewport(v);
            chartTop.setCurrentViewport(v);

            chartTop.setZoomType(ZoomType.HORIZONTAL);
        }

        private void generateLineData(int color, float range) {
            // Cancel last animation if not finished.
            chartTop.cancelDataAnimation();

            // Modify data targets
            Line line = lineData.getLines().get(0);// For this example there is always only one line.
            line.setColor(color);
            for (PointValue value : line.getValues()) {
                // Change target only for Y value.

                value.setTarget(value.getX(), value.getY());


            }

            // Start new data animation with 300ms duration;
            chartTop.startDataAnimation(300);
        }


        private class ValueTouchListener implements ColumnChartOnValueSelectListener {

            ProgressDialog    pd;

            @Override
            public void onValueSelected(int columnIndex, int subcolumnIndex, final SubcolumnValue value) {
                SharedPreferences sharedPreferences = SharedPreferences.getInstance();
                Integer loginId = sharedPreferences.getInt("loginId", 0);
                String date;
                if (btnid == 4) {
                    for (int i = 1; i <= 12; i++) {


                        if (columnIndex == i - 1) {
                            if (i < 10) {
                                date = "2016-0" + i;
                            } else {
                                date = "2016-" + i;
                            }
                            getcountforday("1", loginId, date, i);
                            pd = ProgressDialog.show(getContext(), "", "加载中，请稍后……");
                        }
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pd.dismiss();
                            generateInitialLineData();
                            generateLineData(value.getColor(), 100);
                        }
                    },2000);


                } else if (btnid == 5) {

                    for (int i = 1; i <= 12; i++) {


                        if (columnIndex == i - 1) {
                            if (i < 10) {
                                date = "2016-0" + i;
                            } else {
                                date = "2016-" + i;
                            }
                            getcountforday("2", loginId, date, i);
                            pd = ProgressDialog.show(getContext(), "", "加载中，请稍后……");
                        }
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pd.dismiss();
                            generateInitialLineData();
                            generateLineData(value.getColor(), 100);
                        }
                    },2000);

                } else if (btnid == 6) {
                    for (int i = 1; i <= 12; i++) {


                        if (columnIndex == i - 1) {
                            if (i < 10) {
                                date = "2016-0" + i;
                            } else {
                                date = "2016-" + i;
                            }
                            getcountforday("3", loginId, date, i);
                            pd = ProgressDialog.show(getContext(), "", "加载中，请稍后……");
                        }
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pd.dismiss();
                            generateInitialLineData();
                            generateLineData(value.getColor(), 100);
                        }
                    },2000);

                } else {

                }







            }


            @Override
            public void onValueDeselected() {

                generateLineData(ChartUtils.COLOR_GREEN, 0);

            }
        }
        public void getreceivecountformonth(Integer[]a){
            this.countformonthaaa=a;

        }
        public void  getcountforday(final String posttype,int loginId,String date,final int i){

            try{
                String url="http://oa24406206.carp.mopaasapp.com/";
                url=url+"findByLoginIdAndDate";
                FormBody formBody=new FormBody.Builder()
                        .add("posttype",posttype)
                        .add("loginId",String.valueOf(loginId))
                        .add("date",date)
                        .build();

                HttpClient.post(url,formBody,new HttpResponseHandler(){
                    @Override
                    public void onSuccess(int statusCode, String content) {
                        System.out.println("成功:"+content);


                        Integer countformonth1[] =new Integer[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
                        Integer countformonth2[] =new Integer[31];
                        if(btnid==4){
                            countformonth2=returnmonthforreceive(content,i,countformonth1);
                        }else if(btnid==5){
                            countformonth2= returnmonthdelivery(content,i,countformonth1);
                        }else if(btnid==6){
                            countformonth2= returnmonthforsign(content,i,countformonth1);
                        }



                        getreceivecountformonth(countformonth2);
//                    String s = "";
//                    for(int i=0;i<countformonth.length;i++){
//                        s = s + countformonth[i]+" ";//拼接成字符串，最终放在变量s中
//                    }
//                    SharedPreferences sharedPreferences=SharedPreferences.getInstance();
//                    sharedPreferences.putString("receivecountformonth",s);


                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        super.onFailure(request, e);
                        System.out.println("获取失败:");
                    }
                });
            }catch(Exception e){
                e.printStackTrace();
            }


        }
        public Integer[] returnmonthforreceive(String content,int i,Integer countformonth1[]){
            Gson gson =new Gson();
            Type listType = new TypeToken<List<ViewCount>>() {
            }.getType();

            list1= gson.fromJson(content,listType);
            for (ViewCount viewcount : list1) {
                String time;
                for(int j=0;j<31;j++){
                    if(i<10){
                        time=null;
                        time="2016-0"+i+"-"+days[j];
                    }else{
                        time=null;
                        time="2016-"+i+"-"+days[j];
                    }
                    if (viewcount.getReceive_time().contains(time)) {
                        countformonth1[j]=viewcount.getReeceive_count();
                    }
                }
            }
            return  countformonth1;
        }
        public Integer[] returnmonthdelivery(String content,int i,Integer countformonth1[]){
            Gson gson =new Gson();
            Type listType = new TypeToken<List<delivery_view>>() {
            }.getType();

            list2= gson.fromJson(content,listType);
            for (delivery_view delivery : list2) {
                String time;
                for(int j=0;j<31;j++){
                    if(i<10){
                        time=null;
                        time="2016-0"+i+"-"+days[j];
                    }else{
                        time=null;
                        time="2016-"+i+"-"+days[j];
                    }
                    if (delivery.getDelivery_time().contains(time)) {
                        countformonth1[j]=delivery.getDelivery_count();
                    }
                }
            }
            return  countformonth1;
        }
        public Integer[] returnmonthforsign(String content,int i,Integer countformonth1[]){
            Gson gson =new Gson();
            Type listType = new TypeToken<List<sign_view>>() {
            }.getType();

            list3= gson.fromJson(content,listType);
            for (sign_view sign : list3) {
                String time;
                for(int j=0;j<31;j++){
                    if(i<10){
                        time=null;
                        time="2016-0"+i+"-"+days[j];
                    }else{
                        time=null;
                        time="2016-"+i+"-"+days[j];
                    }
                    if (sign.getSign_time().contains(time)) {
                        countformonth1[j]=sign.getSign_count();
                    }
                }
            }
            return  countformonth1;
        }
    }

}